package com.gree.framework.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.gree.framework.entity.CusUserDetails;
import com.gree.framework.entity.SysUser;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;

import java.util.Collection;
import java.util.LinkedHashMap;

public class SecurityUtils {

    public static Collection<? extends GrantedAuthority> getAuthorities()
    {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Collection<? extends GrantedAuthority> collection = authentication.getAuthorities();
        return collection;
    }

    /**
     * 180681
     */
    public static String getClientId(){
        String clientId = "";
        OAuth2Authentication oAuth2Authentication = null;
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if(authentication instanceof OAuth2Authentication){
            oAuth2Authentication = (OAuth2Authentication)authentication;
            LinkedHashMap<String,Object> map = (LinkedHashMap<String, Object>) oAuth2Authentication.getUserAuthentication().getDetails();
            clientId = map.get("client_id")==null?"":map.get("client_id").toString();
        }

        return clientId;
    }

    public static String getOracleUsername(){
        String gscmClient = "gscm_client";
        return gscmClient.equals(getClientId())?"greescmdb2":getClientId();
    }

    public static CusUserDetails getUser()
    {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LinkedHashMap<String,Object> map = (LinkedHashMap<String, Object>) authentication.getPrincipal();
        CusUserDetails cusUserDetails = JSON.parseObject(JSON.toJSONString(map), new TypeReference<CusUserDetails>(){});
        return cusUserDetails;
    }

    public static LinkedHashMap getUserWithPasswordMode()
    {
        LinkedHashMap<String,Object> map = new LinkedHashMap<>();
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if(authentication instanceof OAuth2Authentication) {
            OAuth2Authentication oAuth2Authentication = (OAuth2Authentication) authentication;
            if(oAuth2Authentication.getUserAuthentication() instanceof UsernamePasswordAuthenticationToken) {
                UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = (UsernamePasswordAuthenticationToken) oAuth2Authentication.getUserAuthentication();
                map = (LinkedHashMap)usernamePasswordAuthenticationToken.getPrincipal();
            }
        }
        return map;
    }
}
